<?php 

namespace Model;

class RegisterHandler 
{
	//skapar databas objekt 
	private $database = null;
	const ALL_PASS_WRONG = 0;
	const EMPTY_FIELD = 1;
	const USER_USED = 2;
	const WRONG_PASS_FORMAT =3;
	const REG_ACCEPT= 4;
	public function __construct ($a_database)
	{
		$this->database = $a_database;
	} 
	public function RegisterUser($newUname, $newPword, $samePword)
	{
	// kollar om man skrivit i formuläret 	
		if (isset($newUname) && isset($newPword) && isset($samePword))
		{
			// kolalr om lösenorden är samma 
			if($newPword != $samePword)
			{
				return self::ALL_PASS_WRONG;
			}
			//kollar om det är i fyllt 
			if ($newUname == "" || $newPword == '') 
			{
				return self::EMPTY_FIELD; 
			}
			// kollar om använadar namnet redan finns 
			if ($stmt = $this->database->Prepare('SELECT * FROM user WHERE Username =?'))
			{
				$stmt->bind_param('s', $newUname);
				$stmt->execute();
				$stmt->bind_result($dbUserId, $dbUsername, $dbPassWord);
				while($stmt->fetch())
				{
					if($newUname == $dbUsername)
					{
						$stmt->close();
						return self::USER_USED;
					}
				}
				$stmt->close();
			}
			// lägger till den nya använadaren 
			$vali = new \Common\Validation();
			if($vali->filterJavascript($newUname) && $vali->validatePassword($newPword))
			{
				if ($stmt = $this->database->Prepare('INSERT INTO user (username, password ) VALUES (?,?)'))
				{
					$password = md5($newPword);
					$stmt->bind_param('ss', $newUname, $password);
					$stmt->execute();
					$stmt->close();
					return self::REG_ACCEPT; 

				}
			}
			
		return self::WRONG_PASS_FORMAT; 
		}
	}
	// funktion för att radera användare (shit)
	public function DeleteUser ($newUname)
	{
		if (isset ($newUname))
		{
			if($stmt = $this->database->Prepare('DELETE FROM user WHERE Username = ?'))
			{
				$stmt->bind_param('s', $newUname);
				$stmt->execute();
				$stmt->close();
				return true;
			}
		}
		return false;
	}
}

